#!/bin/sh

echo -e "=== \033[34mNeutron Panel Installer\033[0m ==="


CURRENT_DIR=$(pwd)

ALL_SETP=10
NOW_SETP=1
PY_VERSION_FLAG=""

exit_func() {
    cd $CURRENT_DIR
    exit $1
}

if [ "$EUID" -ne 0 ]; then
    echo -e "[\033[31mERROR\033[0m] 请使用 root 用户执行脚本！"
    exit_func 1
fi


update(){
    echo -e "[\033[34mINFO\033[0m] 开始升级"
    cd /opt/neutron/neutron
    neu-stop
    echo -e "[\033[34mINFO\033[0m] 升级工具"
    bash -c "yes | ${PY_VERSION_FLAG} -m pip uninstall neutools -y --break-system-packages"
    bash -c "yes | ${PY_VERSION_FLAG} -m pip install neutools --break-system-packages"
    neutools --install-completion
    echo -e "[\033[34mINFO\033[0m] 备份旧数据"
    mv config ../config.bak
    echo -e "[\033[34mINFO\033[0m] 拉取代码"
    git fetch origin
    git reset --hard origin/master
    echo -e "[\033[34mINFO\033[0m] 重构环境"
    install_venv_sc
    echo -e "[\033[34mINFO\033[0m] 还原旧数据"
    mv ../config.bak config
    neu-start
    echo -n -e "\n\n    『"
    wget -q -O - https://v1.hitokoto.cn/?encode=text
    echo -e "』"
    echo -e "          一言来自 hitokoto.cn\n\n"
    echo -e "[\033[34mINFO\033[0m] 升级完成"
    exit_func 0
}

uninstall(){
    echo -e "[\033[34mINFO\033[0m] 开始卸载"
    neu-stop
    rm -rf /opt/neutron
    rm -f /usr/bin/neu-start
    rm -f /usr/bin/neu-stop
    rm -f /usr/bin/neu-stat
    rm -f /etc/systemd/system/neutron.service
    bash -c "yes | ${PY_VERSION_FLAG} -m pip uninstall neutools -y --break-system-packages"
    echo -n -e "\n\n    『"
    wget -q -O - https://v1.hitokoto.cn/?encode=text
    echo -e "』"
    echo -e "          一言来自 hitokoto.cn\n\n"
    echo -e "[\033[34mINFO\033[0m] 卸载完成"
    exit_func 0
}

remove_old() {
    if [ -d "/opt/neutron" ]; then
        echo -e "[\033[34mINFO\033[0m] 升级/移除操作"
        echo -e "[\033[34mINFO\033[0m] 升级操作是安全的，不会清除数据，但有时并不能很好解决问题"
        echo -e "[\033[34mINFO\033[0m] 覆盖安装将会清除所有数据"
        echo -e "[\033[34mINFO\033[0m] 你也可以选择卸载面板"
        echo -e "[\033[34mINFO\033[0m] (y)覆盖安装 (u)升级 (r)卸载 (n)退出脚本"
        read -n 1 -p "是否继续? (y/U/r/n): " choice
        echo ""

        if [ "$choice" == "n" ]; then
            exit_func 1
        elif [ "$choice" == "r" ]; then
            uninstall
            exit_func 1
        elif [ "$choice" == "u" ]; then
            update
            exit_func 1
        elif [ "$choice" == "y" ]; then
            true
        else
            update
            exit_func 1
        fi

        rm -rf /opt/neutron
        $PY_VERSION_FLAG -m pip uninstall neutools -q --break-system-packages -y
    fi
}

# 换源
pip_change_source() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 换源"
    NOW_SETP=$(($NOW_SETP+1))

    local choice=""
    read -n 1 -p "是否更换 pip 源到清华镜像站? (Y/n): " choice
    echo ""

    if [ "$choice" == "n" ]; then
        return
    fi
    $PY_VERSION_FLAG -m pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
}

# 检查 Python
check_python() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 检查 Python 版本"

    local python_versions=("python3.14" "python3.13" "python3.12" "python3.11" "python3")

    for version in "${python_versions[@]}"; do
        if command -v "$version" &> /dev/null; then
            PY_VERSION_FLAG=${version}
            break
        fi
    done

    if [ -z "$PY_VERSION_FLAG" ]; then
        echo -e "[\033[31mERROR\033[0m] Python 版本需要 >= 3.11"
        exit_func 1
    fi

    echo -e "[\033[34mINFO\033[0m] 使用 Python 版本: ${PY_VERSION_FLAG}"

    NOW_SETP=$(($NOW_SETP+1))

    pip_change_source
}

# 源码安装 plocate
install_plocate() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 安装 plocate"
    NOW_SETP=$(($NOW_SETP+1))
    if command -v plocate &> /dev/null; then
        return
    fi
    dnf install gcc-c++ cmake liburing libzstd libzstd-devel libatomic libatomic.so.1 -y
    cd /tmp
    mkdir plocate
    cd plocate
    wget https://plocate.sesse.net/download/plocate-1.1.23.tar.gz
    tar -xzf plocate-1.1.23.tar.gz
    cd plocate-1.1.23
    $PY_VERSION_FLAG -m pip install meson ninja -q --break-system-packages
    ls
    meson setup obj
    cd obj
    ninja
    ninja install
    systemctl enable --now plocate-updatedb.timer
    getent group plocate || groupadd plocate
    cd /tmp
    rm -rf plocate

}

# 安装软件包
install_packages() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 安装软件包"
    if command -v dnf &> /dev/null; then
        dnf install -y python3.12 python3.12-pip
        dnf install -y wget zstd
        dnf install -y git
    elif command -v apt &> /dev/null; then
        apt update
        apt install -y plocate
        apt install -y git
        apt install -y wget
        apt install -y zstd
    elif command -v pacman &> /dev/null; then
        pacman -Sy plocate -q --needed --noconfirm
        pacman -S git -q --needed --noconfirm
        pacman -S wget -q --needed --noconfirm
        pacman -S zstd -q --needed --noconfirm
    fi

    NOW_SETP=$(($NOW_SETP+1))
}

# 下载代码
download_code() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 下载代码"
    cd /opt
    mkdir neutron
    cd neutron
    git clone https://gitee.com/cxy_kevin/neutron.git --depth 1

    NOW_SETP=$(($NOW_SETP+1))
}

# 设置环境
install_venv_sc(){
    cd /opt/neutron/neutron
    $PY_VERSION_FLAG -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
}
install_venv() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 设置环境"

    install_venv_sc

    NOW_SETP=$(($NOW_SETP+1))
}

# 设置启动脚本
install_sh() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 即将完成"

    echo "#!/bin/bash" >> /opt/neutron/start.sh
    echo "source /opt/neutron/neutron/venv/bin/activate" >> /opt/neutron/start.sh
    echo "cd /opt/neutron/neutron" >> /opt/neutron/start.sh
    echo "python main.py" >> /opt/neutron/start.sh
    
    echo '
    [Unit]
    Description=Neutron Panel
    After=network.target
    [Service]
    ExecStart=/opt/neutron/start.sh
    [Install]
    WantedBy=multi-user.target
    ' >> /etc/systemd/system/neutron.service

    echo "python main.py" >> /opt/neutron/start.sh

    chmod +x /opt/neutron/start.sh

    echo -e "#!/bin/bash\nsystemctl start neutron" > /usr/bin/neu-start
    echo -e "#!/bin/bash\nsystemctl stop neutron" > /usr/bin/neu-stop
    echo -e "#!/bin/bash\nsystemctl status neutron" > /usr/bin/neu-stat

    chmod +x /bin/neu-start
    chmod +x /bin/neu-stop
    chmod +x /bin/neu-stat

    systemctl enable neutron

    NOW_SETP=$(($NOW_SETP+1))
}

install_tools() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 安装工具"

    bash -c "yes | ${PY_VERSION_FLAG} -m pip install neutools --break-system-packages"
    neutools --install-completion

    NOW_SETP=$(($NOW_SETP+1))
}

set_config() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 配置信息"

    echo "请输入面板用户名:"
    read -p "面板用户名: " panel_username
    while [ -z "$panel_username" ]; do
        echo "请输入面板用户名:"
        read -p "面板用户名: " panel_username
    done
    echo "请输入面板密码(注：密码会被明文保存在服务器上):"
    read -p "面板密码: " panel_password
    while [ -z "$panel_password" ]; do
        echo "请输入面板密码:"
        read -p "面板密码: " panel_password
    done
    echo "请输入面板安全入口(默认login):"
    read -p "安全入口: " panel_login
    if [ -z "$panel_login" ]; then
        panel_login="login"
    fi
    echo "请输入面板端口(默认1231):"
    read -p "面板端口: " panel_port
    if [ -z "$panel_port" ]; then
        panel_port="1231"
    fi

    mkdir /opt/neutron/neutron/config
    echo "[account]">/opt/neutron/neutron/config/config.toml
    echo "username = \"${panel_username}\"" >>/opt/neutron/neutron/config/config.toml
    echo "password = \"${panel_password}\"" >>/opt/neutron/neutron/config/config.toml
    echo "[server]">>/opt/neutron/neutron/config/config.toml
    echo "port = \"${panel_port}\"" >>/opt/neutron/neutron/config/config.toml
    echo "[security]">>/opt/neutron/neutron/config/config.toml
    echo "loginpath = \"${panel_login}\"" >>/opt/neutron/neutron/config/config.toml

    echo -n -e "\n\n    『"
    wget -q -O - https://v1.hitokoto.cn/?encode=text
    echo "』"
    echo "          一言来自 hitokoto.cn"
    echo -e "\n\n    您可在稍后访问 \"\033[34mhttp://<您的服务器IP>:${panel_port}/${panel_login}\033[0m\" 使用面板\n    请确保防火墙已放行对应端口\n"

    NOW_SETP=$(($NOW_SETP+1))
}

start_service() {
    echo -e "[\033[32m${NOW_SETP}\033[0m/\033[32m${ALL_SETP}\033[0m] 启动服务"
    neu-start
    NOW_SETP=$(($NOW_SETP+1))
}

install_packages
check_python
remove_old
install_plocate
download_code
install_tools
install_venv
install_sh
set_config
start_service


exit_func 0